package cn.edu.lingnan.util;

import org.xml.sax.SAXException;

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.io.IOException;

public class XmlValidater {
    //输入参数：XML和XSD两个文件，只能两个文件名；输出参数：成功或失败
    public static boolean validator(String _xmlFileName,String _xsdFileName) {
        boolean flag = false;
        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
            File file = new File(_xsdFileName);
            Schema schema = schemaFactory.newSchema(file);
            Validator validator = schema.newValidator();
            StreamSource streamSource = new StreamSource(_xmlFileName);
            validator.validate(streamSource);
            flag=true;
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            System.out.println("[DEBUG]XML验证器验证失败......");
            throw new RuntimeException(e);
        }
        return flag;
    }
}
